package controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;






import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import service.StoreManager;
import util.DataUtil;
import vo.Commodity;
import vo.CommodityItem;
import vo.OrderForm;
import vo.Store;
import vo.StoreAddress;

import com.foodshop.admin.jms.AdminJMS;

@Controller
public class StoreManagerController {

	@Autowired(required = true)
	private StoreManager sm;

	@Autowired(required = true)
	private AdminJMS ajms;

	private File destFile_image;

	private String path;

	private static String email;

	@RequestMapping("/storeLogin")
	public String login(String email, String passwd, HttpServletRequest request,HttpServletResponse response) {
		Store s = sm.login(email, passwd);
		System.out.println(s);
		if (s == null) {
			return "login";
		}
		request.getSession().setAttribute("id", s.getStoreId());
		request.getSession().setAttribute("email", s.getEmail());
		this.email = email;
		request.setAttribute("email", s.getEmail());
		if (s.getStatus() == 2) {
			request.getSession().setAttribute("s", s);
			MyListenerQueue();
			return "index";
		} else {
			return "login";
		}
	
	}

	
	@RequestMapping("/updatePasswd")
	@ResponseBody
	public Store updatePasswd(Store store,String newpassword) {
		
		System.out.println("this is updatepasswd:" + store.getEmail() + store.getPasswd() + newpassword);
		store =  sm.login(store.getEmail(),store.getPasswd());
		if (store != null) {
			System.out.println("update success");
			return sm.updatePasswd(store.getEmail(),store.getPasswd(),newpassword);
		}
		System.out.println("update fail");
		store = new Store();
		return store;
				
	}
	/**
	 * File obverseCardPhoto, File reverseCardPhoto, File shopfrontPhoto, File
	 * shopinsidePhoto, File businessLicense, File cateringServiceLicense,
	 * 
	 * @param s
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/storeApply")
	public String apply(Store s, StoreAddress address, HttpServletRequest request, HttpServletResponse response,
			Model model) throws Exception {

		/**
		 * 1銆佷娇鐢ㄤ笂浼犱笁姝ワ紝鎶婅〃鍗曟暟鎹皝瑁呭埌Product瀵硅薄涓�
		 */
		// 鍒涘缓宸ュ巶
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 鑾峰緱瑙ｆ瀽鍣�
		ServletFileUpload sfu = new ServletFileUpload(factory);
		// 浣跨敤瑙ｆ瀽鍣ㄨВ鏋恟equest瀵硅薄锛屽緱鍒癓ist<FileItem>
		List<FileItem> fileItemList = sfu.parseRequest(request);
		// 灏佽fileItemList涓殑鐩稿叧鐨勬暟鎹埌Product瀵硅薄涓�

		/**
		 * 鍏堝皢鏅�氳〃鍗曞瓧娈靛皝瑁呭埌Map涓� 鍐嶆妸Map涓殑鏁版嵁灏佽鍒癙roduct瀵硅薄涓�
		 */
		// 淇濊瘉涓婁紶鏂囦欢鐨勫墠缂�鍜岀敤鎴风殑ID鏄竴鑷寸殑锛屽苟涓斾繚璇佸敮涓�鎬�
		String savePath_image = request.getServletContext().getRealPath("/uploadStore");
		// 灏佽鏅�氭暟鎹埌Product瀵硅薄涓箣鍚庡湪杩涜鏂囦欢璺緞鐨勪繚瀛樺拰鏂囦欢鐨勮嚜韬殑涓婁紶
		Map<String, String> map = new HashMap<String, String>();
		for (FileItem fileItem : fileItemList) {
			if (fileItem.isFormField()) {
				map.put(fileItem.getFieldName(), fileItem.getString("utf-8"));
			}else {
				destFile_image = new File(savePath_image, map.get("email") + "_" + fileItem.getName());
				fileItem.write(destFile_image);
				path = "http://127.0.0.1/StoreSystem/uploadStore/" + (map.get("email") + "_" + fileItem.getName());
				if (s.getObverseCardPhoto() == null) {
					s.setObverseCardPhoto(path);
				}else if(s.getReverseCardPhoto() == null){
					s.setReverseCardPhoto(path);
				}else if (s.getShopfrontPhoto() == null) {
					s.setShopfrontPhoto(path);
				}else if (s.getShopinsidePhoto()==null) {
					s.setShopinsidePhoto(path);
				}else if (s.getBusinessLicense() == null) {
					s.setBusinessLicense(path);
				}else {
					s.setCateringServiceLicense(path);
				}
				
			}
			
		}

		address.setCity(map.get("city"));
		address.setDetailAddress(map.get("detailAddress"));
		address.setProvince(map.get("province"));
		address.setTown(map.get("town"));

		s.setComplainNum(0);
		s.setDetails(map.get("details"));
		s.setEmail(map.get("email"));
		s.setMobile(map.get("mobile"));
		s.setPasswd(map.get("passwd"));
		System.out.println(s.getPasswd());
		s.setQq(map.get("qq"));
		s.setSellerAddress(address);
		s.setSellerName(map.get("sellerName"));
		s.setShopName(map.get("shopName"));
		s.setStatus(DataUtil.STORE_STATUS_CHECKED_UNREGIST);
		s.setTele(map.get("tele"));
		s.setType(map.get("type"));
		System.out.println(s);
		int rs = sm.apply(s);
		if (rs > 0) {
			ajms.sendTextMessage(s.getEmail(), DataUtil.STORE_QUEUE_GET_NEWNUMBER);
			return "login";
		} else
			return "storeApply";
	}

	@RequestMapping("/findStoreInfoByEmail")
	@ResponseBody
	public Store findStoreInfoByEmail(String email,HttpServletRequest request) {

		Store s = null;
		
		String eString = (String)request.getAttribute("email");
		if (eString==null) {
			eString = email;
		}
		s = sm.getInfoByEmail(email, s);
		System.out.println( email + s.toString());
		System.out.println(JSONObject.fromObject(s).toString());
		return s;
	}
	
	@RequestMapping("/showFood")
	@ResponseBody
	public List<Commodity> showFood(HttpServletRequest request,HttpServletResponse response) {
		

		return sm.findFood((String)request.getSession().getAttribute("email"));
		
		
	}
	
	@RequestMapping("/alterStoreStatus")
	public String alterStoreStatus(String email,String status) {
		System.out.println("==============");
		
		if (sm.alterStatus(email,Integer.valueOf(status))) {
			return "redirect:login.html";
		} else {
			return "redirect:applyFail.jsp";
		}

	}
	
	@RequestMapping("/addFood")
	public String addFood(Commodity commodity, HttpServletRequest request, HttpServletResponse response,
			Model model) throws Exception {
		/**
		 * 1銆佷娇鐢ㄤ笂浼犱笁姝ワ紝鎶婅〃鍗曟暟鎹皝瑁呭埌Product瀵硅薄涓�
		 */
		// 鍒涘缓宸ュ巶
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 鑾峰緱瑙ｆ瀽鍣�
		ServletFileUpload sfu = new ServletFileUpload(factory);
		// 浣跨敤瑙ｆ瀽鍣ㄨВ鏋恟equest瀵硅薄锛屽緱鍒癓ist<FileItem>
		List<FileItem> fileItemList = sfu.parseRequest(request);
		// 灏佽fileItemList涓殑鐩稿叧鐨勬暟鎹埌Product瀵硅薄涓�

		/**
		 * 鍏堝皢鏅�氳〃鍗曞瓧娈靛皝瑁呭埌Map涓� 鍐嶆妸Map涓殑鏁版嵁灏佽鍒癙roduct瀵硅薄涓�
		 */
		// 淇濊瘉涓婁紶鏂囦欢鐨勫墠缂�鍜岀敤鎴风殑ID鏄竴鑷寸殑锛屽苟涓斾繚璇佸敮涓�鎬�
		String savePath_image = request.getServletContext().getRealPath("/uploadCommodity");
		// 灏佽鏅�氭暟鎹埌Product瀵硅薄涓箣鍚庡湪杩涜鏂囦欢璺緞鐨勪繚瀛樺拰鏂囦欢鐨勮嚜韬殑涓婁紶
		Map<String, String> map = new HashMap<String, String>();
		for (FileItem fileItem : fileItemList) {
			if (fileItem.isFormField()) {
				map.put(fileItem.getFieldName(), fileItem.getString("utf-8"));
			}else {
				destFile_image = new File(savePath_image, (String)request.getSession().getAttribute("email") + "_" + fileItem.getName());
				fileItem.write(destFile_image);
				path = "http://127.0.0.1/StoreSystem/uploadCommodity/" + (String)request.getSession().getAttribute("email") + "_" + fileItem.getName();
				commodity.setPictureUri(path);
			}
			
		}

		commodity.setCommodiryNum(Integer.valueOf(map.get("commodiryNum")));
		commodity.setCommodiryStatus(Integer.valueOf(map.get("commodiryStatus")));
		commodity.setCommodityCode(map.get("commodityCode"));
		commodity.setCommodityDiscount(Double.valueOf(map.get("commodityDiscount")));
		commodity.setCommodityName(map.get("commodityName"));
		commodity.setCommodityPrice(Double.parseDouble(map.get("commodityPrice")));
		commodity.setCommodityTip(map.get("commodityTip"));
		commodity.setCommodityType(map.get("commodityType"));
		commodity.setStoreId((Integer)request.getSession().getAttribute("id"));
		int rs = sm.addFood(commodity);
		if (rs > 0) {
			return "showfood";
		} else
			return "fail";

	}
	@RequestMapping("/deleteFood")
	public int deleteFood(String commodityId) {
		
		int id = 0;
		try {
			id = Integer.valueOf(commodityId);
		} catch (Exception e) {
			return id;
		}
		int rs = sm.deleteFood(id);
		return rs;
	}
	
	// 鍟嗗 鐢熸垚璁㈠崟鐨刄RL
		@RequestMapping("/findOrdersByStoreId")
		@ResponseBody
		public String findOrdersByStoreId(HttpServletResponse response,
				HttpServletRequest request) {
			System.out.println("find orders by storeid" );
			response.setCharacterEncoding("UTF-8");
			String storeId = request.getParameter("email");

			System.out.println(storeId);		
			
			List<OrderForm> orders = null;
			List<CommodityItem> items = new ArrayList<CommodityItem>();
			if (storeId != null) {
				orders = sm.findOrdersByStoreId(storeId);

				for (int i = 0; i < orders.size(); i++) {
					List<CommodityItem> items1 = sm.findItemsByOrderId(orders
							.get(i).getOrderNumber());
					for (int j = 0; j < items1.size(); j++) {

						items.add(items1.get(j));

						System.out.println(items.get(j));
					}
				}

				String json1 = JSONArray.fromObject(orders).toString();
				System.out.println(json1);

				String json2 = JSONArray.fromObject(items).toString();
				System.out.println(json2);
				JSONObject json = new JSONObject();

				json.put("orders", json1);

				json.put("items", json2);

				try {
					PrintWriter out = response.getWriter();

					out.print(json);
				} catch (IOException e) {
					e.printStackTrace();
				}
				System.out.println(json);
			}

			return null;
		}

		@RequestMapping("/bindingMail")
		@ResponseBody
		public Store bindingMail(Store store,String newemail, HttpServletRequest request) {
			System.out.println(store.getEmail());
			if (sm.bindingMail(store,newemail)) {
				System.out.println("success");
				email = newemail;
				return store;
			} else {
				System.out.println("fail");
				store.setEmail(null);
				return store;
			}

		}
		
		@RequestMapping("/showOrder")
		@ResponseBody
		public List<OrderForm> showOrder( HttpServletRequest request) {
			
			System.out.println("email:" + email + "," + request.getSession().getAttribute("email"));
			return sm.findOrders(email);

		}
		
		@RequestMapping(value = "/newNumber")
		@ResponseBody
		public String newNumber(HttpServletResponse response) {

			PrintWriter out;
			try {
				if (DataUtil.NEW_NUMBER != 0) {
					out = response.getWriter();
					out.write("1");
					DataUtil.NEW_NUMBER = 0;
					out.flush();
					out.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return "index";
		}
		
		@RequestMapping("deleteTouSuByOrderId")
		@ResponseBody
		public String deleteTouSuByOrderId(Integer orderId){
			System.out.println("鍟嗗鎺ュ彈鍒扮殑orderId"+orderId);
			int result=0;
			
			result=sm.deleteTouSuByOrderId(orderId);
			
			return result+"";
		}


		private void MyListenerQueue(){

			Timer timer = new Timer(true);
			timer.schedule(new TimerTask() {

				@Override
				public void run() {
					
						// 璁㈠崟闃熷垪
						DataUtil.NEW_NUMBER = DataUtil.ReceiveMsg(DataUtil.ADMIN_QUEUE)!=null? 1:0;
						
				
				}
			}, 1000 * 2);
		}

}
